<template>
  <div class="student-list-page">
    <!-- 搜索和筛选区域 -->
    <el-card shadow="never" class="search-card">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="关键词">
          <el-input
            v-model="searchForm.keyword"
            placeholder="输入姓名或学号搜索"
            clearable
            @clear="handleSearch"
            @keyup.enter="handleSearch"
            style="width: 200px"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </el-form-item>

        <el-form-item label="班级">
          <el-select
            v-model="searchForm.class"
            placeholder="选择班级"
            clearable
            @change="handleSearch"
            style="width: 150px"
          >
            <el-option label="全部班级" value="" />
            <el-option
              v-for="cls in classes"
              :key="cls"
              :label="cls"
              :value="cls"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="成绩范围">
          <el-input
            v-model.number="searchForm.minScore"
            placeholder="最低分"
            type="number"
            style="width: 100px"
          />
          <span style="margin: 0 10px">-</span>
          <el-input
            v-model.number="searchForm.maxScore"
            placeholder="最高分"
            type="number"
            style="width: 100px"
          />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="handleReset">
            <el-icon><RefreshLeft /></el-icon>
            重置
          </el-button>
        </el-form-item>

        <el-form-item style="float: right">
          <el-button type="primary" @click="handleAdd">
            <el-icon><Plus /></el-icon>
            新增学生
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 学生列表表格 -->
    <el-card shadow="never" class="table-card">
      <el-table
        :data="students"
        v-loading="loading"
        border
        stripe
        style="width: 100%"
      >
        <el-table-column type="index" label="序号" width="60" align="center" />
        <el-table-column prop="studentId" label="学号" width="120" align="center" />
        <el-table-column prop="name" label="姓名" width="120" align="center" />
        <el-table-column prop="class" label="班级" width="150" align="center" />
        <el-table-column prop="scores" label="课程成绩" min-width="300" align="center">
          <template #default="{ row }">
            <div v-if="row.scores && row.scores.length > 0" class="scores-container">
              <el-tag
                v-for="(course, index) in row.scores"
                :key="index"
                :type="getScoreType(course.score)"
                effect="dark"
                size="small"
                style="margin: 2px 5px"
              >
                {{ course.courseName }}: {{ course.score }}
              </el-tag>
            </div>
            <span v-else style="color: #909399">暂无成绩</span>
          </template>
        </el-table-column>
        <el-table-column label="平均分" width="100" align="center">
          <template #default="{ row }">
            <el-tag :type="getScoreType(getAverageScore(row))" effect="dark">
              {{ getAverageScore(row) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="等级" width="100" align="center">
          <template #default="{ row }">
            {{ getGrade(getAverageScore(row)) }}
          </template>
        </el-table-column>
        <el-table-column prop="createdAt" label="创建时间" width="180" align="center">
          <template #default="{ row }">
            {{ formatDate(row.createdAt) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" fixed="right" width="180" align="center">
          <template #default="{ row }">
            <el-button type="primary" size="small" link @click="handleEdit(row)">
              <el-icon><Edit /></el-icon>
              编辑
            </el-button>
            <el-button type="danger" size="small" link @click="handleDelete(row)">
              <el-icon><Delete /></el-icon>
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.limit"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handlePageChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getStudents, deleteStudent, getClasses } from '@/api/student'

const router = useRouter()

// 搜索表单
const searchForm = reactive({
  keyword: '',
  class: '',
  minScore: null,
  maxScore: null
})

// 学生列表
const students = ref([])
const loading = ref(false)
const classes = ref([])

// 分页
const pagination = reactive({
  page: 1,
  limit: 10,
  total: 0
})

// 加载学生列表
const loadStudents = async () => {
  loading.value = true
  try {
    const params = {
      page: pagination.page,
      limit: pagination.limit,
      keyword: searchForm.keyword,
      class: searchForm.class
    }

    if (searchForm.minScore !== null && searchForm.minScore !== '') {
      params.minScore = searchForm.minScore
    }
    if (searchForm.maxScore !== null && searchForm.maxScore !== '') {
      params.maxScore = searchForm.maxScore
    }

    const res = await getStudents(params)
    students.value = res.data
    pagination.total = res.pagination.total
  } catch (error) {
    ElMessage.error('加载学生列表失败')
  } finally {
    loading.value = false
  }
}

// 加载班级列表
const loadClasses = async () => {
  try {
    const res = await getClasses()
    classes.value = res.data
  } catch (error) {
    console.error('加载班级列表失败:', error)
  }
}

// 搜索
const handleSearch = () => {
  pagination.page = 1
  loadStudents()
}

// 重置
const handleReset = () => {
  searchForm.keyword = ''
  searchForm.class = ''
  searchForm.minScore = null
  searchForm.maxScore = null
  handleSearch()
}

// 新增学生
const handleAdd = () => {
  router.push('/students/add')
}

// 编辑学生
const handleEdit = (row) => {
  router.push(`/students/edit/${row._id}`)
}

// 删除学生
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除学生 ${row.name}（学号：${row.studentId}）吗？`,
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    await deleteStudent(row._id)
    ElMessage.success('删除成功')
    loadStudents()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

// 分页大小改变
const handleSizeChange = (size) => {
  pagination.limit = size
  pagination.page = 1
  loadStudents()
}

// 页码改变
const handlePageChange = (page) => {
  pagination.page = page
  loadStudents()
}

// 计算平均分
const getAverageScore = (row) => {
  if (!row.scores || row.scores.length === 0) return 0
  const total = row.scores.reduce((sum, course) => sum + course.score, 0)
  return (total / row.scores.length).toFixed(1)
}

// 获取成绩标签类型
const getScoreType = (score) => {
  if (score >= 90) return 'success'
  if (score >= 80) return 'primary'
  if (score >= 70) return 'info'
  if (score >= 60) return 'warning'
  return 'danger'
}

// 获取成绩等级
const getGrade = (score) => {
  if (score >= 90) return '优秀'
  if (score >= 80) return '良好'
  if (score >= 70) return '中等'
  if (score >= 60) return '及格'
  return '不及格'
}

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return '-'
  const date = new Date(dateString)
  return date.toLocaleString('zh-CN', { 
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

onMounted(() => {
  loadStudents()
  loadClasses()
})
</script>

<style scoped>
.student-list-page {
  max-width: 1400px;
  margin: 0 auto;
}

.search-card {
  margin-bottom: 20px;
}

.search-form {
  margin: 0;
}

.table-card {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.scores-container {
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
  gap: 5px;
}
</style>
